import Vue from 'vue';
import busHolder from '../vue/bus';

import { KEY_JUMP, KEY_SCREEN_REFRESH, KEY_SCOPE_UPDATED } from './screen/events';
import { defaultGeneralTabs, Jump } from './screen/monitor';
import fetcher from './screen/fetcher';
import scoper from './screen/scope';
import '../vue/topnav';
import './ui/aside';
import './ui/monitorTab';

let bus = busHolder.getBus;

import('../vue/ants.js')
  .then(() => {
    let v = new Vue({
      el : '#root',
      data : {
        loading : true,
        title : "加载中...",
        // tab 部分
        tabType : 'general',
        tabItems : defaultGeneralTabs(),
        tabSid : ''
      },
      methods : {
        onLoadMore : function () {
          console.log(bus);
        },

        // 事件接收
        /** @param {Jump} jump */
        onAsideSelected : function (jump) {
          if (jump.aside === this.tabType && jump.asideParam === this.tabSid) {
            return;
          }

          switch (jump.aside) {
          case 'general': case 'screen': case 'screenRemoved':
            this.tabType = jump.aside;
            this.tabSid = jump.asideParam;
            break;
          default:
            console.log('侧边栏无法操作的 key:', key);
            break;
          }
        }
      },
      mounted : function () {
        bus().$on(busHolder.KEY_TOP_NAV_CLICK, (url) => {
          location.href = url;
        });
        bus().$on(KEY_JUMP, (jump) => {
          this.onAsideSelected(jump);
        });

        fetcher.setWebSocketMessageListener(wsMessageDispatcher);
        fetcher.setWebSocketCloseListener(() => {
          this.$message.warning('与服务器的连接已经关闭。建议你刷新该浏览器页面重新获取服务器数据。');
        });
        scoper.setScopeUpdateListener((scope) => wsMessageDispatcher(KEY_SCOPE_UPDATED, {scope}));

        // 从 cookie 中获取当前 scope
        const scope = scoper.getScope();
        fetcher.fetchData(scope)
          .then((array) => {bus().$emit(KEY_SCREEN_REFRESH, array);})
          .then(() => {fetcher.connectWebSocket();})
          .then(() => fetcher.sendScopeUpdated(scope));

        bus().$on(KEY_SCOPE_UPDATED, (obj) => {
          fetcher.fetchData(obj.scope)
            .then((array) => bus().$emit(KEY_SCREEN_REFRESH, array))
            .then(() => fetcher.sendScopeUpdated(obj.scope));
        });
      }
    });
    return v;
  });

function wsMessageDispatcher(type, data) {
  bus().$emit(type, data);
}
